package com.itheima.takeout.ui.adapter;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.daimajia.slider.library.Animations.DescriptionAnimation;
import com.daimajia.slider.library.SliderLayout;
import com.daimajia.slider.library.SliderTypes.BaseSliderView;
import com.daimajia.slider.library.SliderTypes.TextSliderView;
import com.itheima.takeout.MyApplication;
import com.itheima.takeout.R;
import com.itheima.takeout.model.net.bean.Category;
import com.itheima.takeout.model.net.bean.Promotion;
import com.itheima.takeout.model.net.bean.Seller;
import com.itheima.takeout.ui.activity.BusinessActivity;
import com.itheima.takeout.ui.activity.MainActivity;
import com.itheima.takeout.util.Constant;

import java.util.HashMap;
import java.util.List;

/**
 * Created by Tea on 2016/8/25.
 */
public class HomeRecyclerViewAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
    // 分成如下部分：
    // 1、头部（包含：轮播---附近商家）
    // 2、正文部分（包括：全部附近商家+分割+20个其他商家+分割+20个其他商家+……）


    private static final int TYPE_TITLE = 0;
    private static final int TYPE_DIVISION = 1;
    private static final int TYPE_SELLER = 2;

    List<Category> categorieList;
    List<Promotion> promotionList;
    List<Seller> nearbySellerList;
    List<Seller> ortherSellerList;

    public void setCategorieList(List<Category> categorieList) {
        this.categorieList = categorieList;
    }

    public void setPromotionList(List<Promotion> promotionList) {
        this.promotionList = promotionList;
    }

    public void setNearbySellerList(List<Seller> nearbySellerList) {
        this.nearbySellerList = nearbySellerList;
    }

    public void setOrtherSellerList(List<Seller> ortherSellerList) {
        this.ortherSellerList = ortherSellerList;
    }

    private Context mContext;
    private int divisionSum = 0;

    public HomeRecyclerViewAdapter(Context mContext) {
        this.mContext = mContext;
    }


    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        LayoutInflater mInflater = LayoutInflater.from(mContext);
        switch (viewType) {
            case TYPE_TITLE:
                ViewGroup title = (ViewGroup) mInflater.inflate(R.layout.item_title, parent, false);
                TitleViewHolder titleViewHolder = new TitleViewHolder(title);
                return titleViewHolder;
            case TYPE_DIVISION:
                ViewGroup division = (ViewGroup) mInflater.inflate(R.layout.item_division, parent, false);
                DevisionViewHolder devisionViewHolder = new DevisionViewHolder(division);
                return devisionViewHolder;
            case TYPE_SELLER:
                ViewGroup seller = (ViewGroup) mInflater.inflate(R.layout.item_seller, parent, false);
                SellerViewHolder vhGroup = new SellerViewHolder(seller);
                return vhGroup;
        }
        return null;
    }


    private HashMap<Integer, Integer> map = new HashMap<>();

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        System.out.println("holder.getItemViewType = [" + holder.getItemViewType() + "], position = [" + position + "]");
        switch (holder.getItemViewType()) {
            case TYPE_TITLE:
                break;
            case TYPE_DIVISION:
                divisionSum++;
                break;
            case TYPE_SELLER:
                SellerViewHolder sellerViewHolder = (SellerViewHolder) holder;
                // 判断是附近商家还是普通卖家
                if (position - 1 < nearbySellerList.size()) {
//                    setSellerInfo(nearbySellerList.get(position-1),sellerViewHolder);
                    sellerViewHolder.setSeller(nearbySellerList.get(position - 1));
                } else {
                    int index = 0;
                    if (map.get(position) != null) {
                        index = map.get(position);
                    } else {
                        index = position - 1 - nearbySellerList.size() - divisionSum;
                        map.put(position, index);
                    }
                    try {
//                        setSellerInfo(ortherSellerList.get(index),sellerViewHolder);
                        sellerViewHolder.setSeller(nearbySellerList.get(index));
                    } catch (Exception ex) {
                        System.out.println(ex);
                    }
                }
                break;
        }
    }

//    private void setSellerInfo(Seller item,SellerViewHolder holder){
//        holder.mTitle.setText(item.getName());
//        holder.id=item.getId();
//    }


    int divisionCount = 1;

    @Override
    public int getItemCount() {
        if (promotionList == null) {
            return 0;
        }

        divisionCount = 1;
        calcDivision(ortherSellerList.size());
        return nearbySellerList.size() + 1 + ortherSellerList.size() + divisionCount;
    }

    /**
     * Item的Type值定义
     * 0：标题
     * nearbyBusinesses.size+1：第一个分割线
     * nearbyBusinesses.size+1+21：第二个分割线
     * nearbyBusinesses.size+1+21+21：第三个分割线
     *
     * @param position
     * @return
     */
    @Override
    public int getItemViewType(int position) {
        int viewType;
        if (position == 0) {
            viewType = TYPE_TITLE;
        } else if (((position - nearbySellerList.size() - 1) >= 0) && (((position - nearbySellerList.size() - 1) % 21 == 0))) {
            viewType = TYPE_DIVISION;
        } else {
            viewType = TYPE_SELLER;
        }
        return viewType;
    }

    /**
     * 依据ortherBusinesses获取分割线数量
     *
     * @return
     */
    public void calcDivision(int size) {
        //1-20:::::1
        //21-40::::2

        if ((size = size - 20) > 0) {
            divisionCount++;
            calcDivision(size);
        }

    }

    public class DevisionViewHolder extends RecyclerView.ViewHolder {


        public DevisionViewHolder(View itemView) {
            super(itemView);
        }

    }

    public class SellerViewHolder extends RecyclerView.ViewHolder {
        TextView mTitle;
        TextView mCountTitle;
        Seller seller;
        MyApplication application;

        public SellerViewHolder(View itemView) {
            super(itemView);
            mTitle = (TextView) itemView.findViewById(R.id.tv_title);
            mCountTitle= (TextView) itemView.findViewById(R.id.tvCount);
            application = (MyApplication) ((MainActivity) mContext).getApplication();

        }

        public void setSeller(final Seller seller) {
            this.seller = seller;
            mTitle.setText(seller.getName());
           int count = application.queryCacheSelectedInfoBySellerId(seller.getId());
            if(count == 0){
                mCountTitle.setVisibility(View.GONE);
            }else{
                mCountTitle.setVisibility(View.VISIBLE);
                mCountTitle.setText(count+"");
            }
            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(mContext,BusinessActivity.class);
                    Seller s = new Seller();
                    s.setId(seller.getId());
                    s.setName(seller.getName());
                    s.setSendPrice(30);
                    s.setDeliveryFee("9");
                    intent.putExtra("seller",s);
                    s.setPic(Constant.HOST+"/TakeoutService/imgs/item_kfc.png");

                    int count = application.queryCacheSelectedInfoBySellerId(seller.getId());
                    if (count > 0) {
                        intent.putExtra("hasCacheSelected", true);
                    }else{
                        intent.putExtra("hasCacheSelected", false);
                    }

                    mContext.startActivity(intent);
                }
            });
        }
    }

    public class TitleViewHolder extends RecyclerView.ViewHolder {

        SliderLayout sliderLayout;

        public TitleViewHolder(View itemView) {
            super(itemView);

            sliderLayout = (SliderLayout) itemView.findViewById(R.id.slider);

            initSliderLayout();

        }

        private void initSliderLayout() {
            HashMap<String, String> url_maps = new HashMap<String, String>();
            url_maps.put("Hannibal", "http://static2.hypable.com/wp-content/uploads/2013/12/hannibal-season-2-release-date.jpg");
            url_maps.put("Big Bang Theory", "http://tvfiles.alphacoders.com/100/hdclearart-10.png");
            url_maps.put("House of Cards", "http://cdn3.nflximg.net/images/3093/2043093.jpg");
            url_maps.put("Game of Thrones", "http://images.boomsbeat.com/data/images/full/19640/game-of-thrones-season-4-jpg.jpg");


            for (String name : url_maps.keySet()) {
                TextSliderView textSliderView = new TextSliderView(sliderLayout.getContext());
                // initialize a SliderLayout
                textSliderView
                        .description(name)
                        .image(url_maps.get(name))
                        .setScaleType(BaseSliderView.ScaleType.Fit);
//                    .setOnSliderClickListener(this);

                //add your extra information
                textSliderView.bundle(new Bundle());
                textSliderView.getBundle().putString("extra", name);

                sliderLayout.addSlider(textSliderView);
            }

            sliderLayout.setPresetTransformer(SliderLayout.Transformer.Accordion);
            sliderLayout.setPresetIndicator(SliderLayout.PresetIndicators.Center_Bottom);
            sliderLayout.setCustomAnimation(new DescriptionAnimation());
            sliderLayout.setDuration(4000);
        }
    }

}

